package middleware

import (
	"github.com/gin-gonic/gin"

	"Data-API-MCP/backend/configs"
)

// CORS CORS中间件
func CORS(config *configs.Config) gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Writer.Header().Set("Access-Control-Allow-Origin", "*")                                            // 允许所有源
		c.Writer.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")             // 允许所有方法
		c.Writer.Header().Set("Access-Control-Allow-Headers", "Origin, Content-Type, Accept, Authorization") // 允许所有头
		c.Writer.Header().Set("Access-Control-Expose-Headers", "Content-Length")                             // 暴露头
		c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")                                    // 允许凭证
		c.Writer.Header().Set("Access-Control-Max-Age", "86400")                                             // 最大年龄

		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(204) // 中止
			return
		}

		c.Next() // 继续
	}
}
